<?php
namespace app\common\service\translate;

use app\common\service\ConfigService;
use think\Exception;

/**
 * 翻译驱动
 * Class TranslateDriver
 * @package app\common\service\translate
 */
class TranslateDriver
{
    protected static $_instance = null;

    private $engine; // 当前翻译引擎类

    /**
     * 错误信息
     * @var
     */
    protected $error = null;

    /**
     * 架构方法
     * SmsDriver constructor.
     */
    public function __construct()
    {
        // 初始化
        $this->initialize();
    }

    /**
     * @notes 初始化
     * @return bool
     */
    public function initialize()
    {
        try {
            $defaultEngine = ConfigService::get('translate', 'engine', false);
            if($defaultEngine === false) {
                throw new \Exception('请开启翻译配置');
            }
            $classSpace = __NAMESPACE__ . '\\engine\\' . ucfirst(strtolower($defaultEngine)) . 'Translate';

            if (!class_exists($classSpace)) {
                throw new \Exception('没有相应的翻译驱动类');
            }

            $engineConfig = ConfigService::get('translate', strtolower($defaultEngine), false);
            if($engineConfig === false) {
                throw new \Exception($defaultEngine . '未配置');
            }
            if ($engineConfig['status'] != 1) {
                throw new \Exception('翻译服务未开启');
            }

            $this->engine = new $classSpace($engineConfig);
            if(!is_null($this->engine->getError())) {
                throw new \Exception($this->engine->getError());
            }
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * @notes 获取错误信息
     * @return null
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * @notes 获取翻译结果
     * @param $sourceLanguage
     * @param $sourceText
     * @param $targetLanguage
     * @return false
     */
    public function getTranslateText($sourceLanguage,$sourceText,$targetLanguage)
    {
        try {
            $result = $this->engine
                ->setSourceLanguage($sourceLanguage)// 源语言
                ->setSourceTextList($sourceText)// 源文本
                ->setTargetLanguage($targetLanguage) // 目标语言
                ->getTranslateText();
            if(false === $result) {
                throw new \Exception($this->engine->getError());
            }
            return $result;
        } catch(\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

}